import React from 'react'

import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button,Message,Upload,Radio,TreeSelect} from 'antd';
import PcEditor from '../../../components/PcEditor';
import MobileEditor from '../../../components/MobileEditor';
import {INTERFACE_CORE_URL} from '../../../api/config';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const { TextArea } = Input;
import api from '../../../api/user';
import md5 from 'md5';
import './index.less'
import '../../../style/antd-theme.less'


function beforeUpload(file) {
  const isImg = (file.type === 'image/jpeg' || file.type === 'image/gif' || file.type === 'image/png');
  if (!isImg) {
    Message.error('您只能上传图片格式的文件!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    Message.error('上传的图片必须小于等于2MB!');
  }
  return isImg && isLt2M;
}

class UserForm extends React.Component {
  state = {
    confirmDirty: false,
    sumitLoad: false,
  };

  componentWillReceiveProps(nextProps) {
    if (this.props.clearForm != nextProps.clearForm && nextProps.clearForm == false) {
      this.setState({
        imageUrl: '',
      })
      this.props.form.resetFields();
    }
  }

  handleSubmit = (e) => {
    //const {finish} = this.props;
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const result=values.photo.file;
        if(typeof(result) != "undefined"){
          const data=result.response.data;
          values.photo=data.fullPath;
        }

        this.setState({
          sumitLoad: true
        });

        if(values.id){
          this.update(values);
        }else{
          this.add(values);
        }
      }
    });
  }
  update= (values) =>{
  
    if(values.roles){
      for(var i=0;i<values.roles.length;i++){
        values.roles[i].id=values.roles[i].value
        values.roles[i].name=values.roles[i].label
       }
    }
    api.put('/updateUser', {...values}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('修改成功！');
      const { close,refeshData } = this.props;
      refeshData();
      close();
     }else{
      Message.error(result.message);
     }
     this.setState({
      sumitLoad: false
    });
    });
  }


  add= (values) =>{
    delete values["id"];  
    if(values.password){
      values.password=md5(values.password);
    }
    if(values.roles){
      for(var i=0;i<values.roles.length;i++){
        values.roles[i].id=values.roles[i].value
        values.roles[i].name=values.roles[i].label
       }
    }
    api.post('/addUser', {...values}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('添加成功！');
      const { close,refeshData,setUser,isOfficeRelative } = this.props;
      if(isOfficeRelative){
        let data = result.data;
        setUser({
          id:data.id,
          name:data.name
        });
      }else{
        refeshData();
      }
      close();
     }else{
      Message.error(result.message);
     }
     this.setState({
      sumitLoad: false
    });
    });
  }

  handleConfirmBlur = (e) => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  }
  checkPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次输入的密码不一样，请重试!');
    } else {
      callback();
    }
  }
  checkConfirm = (rule, value, callback) => {
    const form = this.props.form;
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  }

  handleImageChange = (info) => {
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      if(info.file.response){
        this.setState({ imageUrl:info.file.response.data.fullPath + '?process=image/resize,width_150,height_150'})
      }
    }
  }
  clearPho = () => {
    this.setState({
      imageUrl:undefined
    });
  }

  validLoginNameRule = (rule, value, callback) => {
    const form = this.props.form;
    const loginName=form.getFieldValue('loginName');
    api.get('/sysUser/getUserTargetCount', {"value":loginName}).then((data) => {
      const result= data.data;
      const user = this.props.user;
      if(user && user.loginName == loginName){
        callback();
        return;
      }
     if(result.count > 0){
      callback('登录名重复，请重新输入!');
     }else{
      callback();
     }
    });
  }


  render() {
    const { getFieldDecorator,resetFields } = this.props.form;
    const { close , callbackParent ,roles,user,offices,isOfficeRelative } = this.props;
    const _this = this;
    const imageUrl = this.state.imageUrl;
    const plainOptions = [
      { label: '系统用户', value: 1 },
      { label: '微信用户', value: 2 },
      { label: '平台用户', value: 3 },
    ];
  let imgStyle={};
  if(user){
    user.widthImg=user.photo+"?process=image/resize,width_150,height_150";
    let url="";
    if(imageUrl){
      url=imageUrl;
    }else{
      url=user.widthImg;
    }
    imgStyle={background:"url("+url+") center center no-repeat"};
  }else{
    imgStyle={background:"url("+imageUrl+") center center no-repeat"};
  }

    // 把重置表单的方法传给父亲
    callbackParent({
      resetFields:resetFields,
      clearPho:this.clearPho
    });

    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 16 },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 14,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 6,
        },
      },
    };
    const prefixSelector = getFieldDecorator('prefix', {
      initialValue: '86',
    })(
      <Select className="icp-selector">
        <Option value="86">+86</Option>
      </Select>
    );
    return (
      <Form onSubmit={this.handleSubmit}>
        {getFieldDecorator('id', {
            initialValue:user?user.id:''
          })(
            <input type="hidden" />
          )}
        {getFieldDecorator('userType', {
            initialValue:user?user.userType:1
          })(
            <input type="hidden" />
          )}
        <FormItem
          {...formItemLayout}
          label="用户头像"
          hasFeedback
        >
          {getFieldDecorator('photo', {
            rules: [{
              required: true, message: '请上传一个头像图片!',
            }],
            initialValue:user?user.photo:''
          })(
            <Upload
              className="avatar-uploader"
              name="file"
              showUploadList={false}
              action={INTERFACE_CORE_URL+"/upload"}
              beforeUpload={beforeUpload}
              onChange={_this.handleImageChange}
              accept="image/*"
            >
              {
                user ? 
                  (imageUrl || user.photo) ?
                  <div style={imgStyle} className="avatar" ></div> :
                  <Icon type="plus" className="avatar-uploader-trigger" />
                  : 
                  (imageUrl) ?
                  <div style={imgStyle} className="avatar" ></div> :
                  <Icon type="plus" className="avatar-uploader-trigger" />
              }
            </Upload>
          )}
        </FormItem>
        {isOfficeRelative?
          '':
          <FormItem
            {...formItemLayout}
            label="所属机构"
            hasFeedback
          >
            {getFieldDecorator('officeId', {
              rules: [ {
                required: true, message: '请选择一个机构后提交!',
              }],
              initialValue:user?user.officeId:''
            })(
              <TreeSelect
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={offices}
                placeholder="请选择一个机构"
                treeDefaultExpandAll
              />
            )}
          </FormItem>
        }
        <FormItem
          {...formItemLayout}
          label={(
            <span>
              用户工号&nbsp;
              <Tooltip title="你所在公司的工号，没有可不填写">
                <Icon type="question-circle-o" />
              </Tooltip>
            </span>
          )}
          hasFeedback
        >
          {getFieldDecorator('no', {
            initialValue:user?user.no:''
          })(
            <Input type="text"/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="姓名"
          hasFeedback
        >
          {getFieldDecorator('name', {
            rules: [{
              required: true, message: '请输入您的姓名后提交!',
            }],
            initialValue:user?user.name:''
          })(
            <Input type="text"/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label={(
            <span>
              登录名&nbsp;
              <Tooltip title="你登录时使用的帐号名，登录名不可修改且唯一">
                <Icon type="question-circle-o" />
              </Tooltip>
            </span>
          )}
          hasFeedback
        >
          {getFieldDecorator('loginName', {
            rules: [
              { required: true, message: '请输入一个登录名!' }, 
              { validator: this.validLoginNameRule}],
            initialValue: user ? user.loginName : '',
          })(
            <Input type="text" />
          )}
        </FormItem>
        {user?'':
          <FormItem
              {...formItemLayout}
              label="密码"
              hasFeedback
            >
            {getFieldDecorator('password', {
              rules: [{
                required: true, message: '请输入一个密码信息!',
              }, {
                validator: this.checkConfirm,
              }],
            })(
              <Input type="password"/>
            )}
          </FormItem>
        }
        {user?'':
          <FormItem
            {...formItemLayout}
            label="确认密码"
            hasFeedback
          >
            {getFieldDecorator('confirm', {
              rules: [{
                required: true, message: '请输入您的确认密码信息!',
              }, {
                validator: this.checkPassword,
              }],
            })(
              <Input type="password" onBlur={this.handleConfirmBlur} />
            )}
          </FormItem>
        }
        <FormItem
          {...formItemLayout}
          label="邮箱地址"
          hasFeedback
        >
          {getFieldDecorator('email', {
            rules: [{
              type: 'email', message: '请输入一个正确的E-mail!',
            }],
            initialValue:user?user.email:''
          })(
            <Input type="text"/>
          )}
        </FormItem>
        {/* <FormItem
            {...formItemLayout}
            label="活动介绍">
            <div id="description">
                {getFieldDecorator('description', {
                    rules: [{
                        required: true, message: '请填写活动介绍'
                    },{
                      min: 100, message: '必须大于100个字符!'
                    }],
                    initialValue:user?'':''
                })(
                    <PcEditor id="description"/>
                )}
            </div>
        </FormItem>
        <FormItem
            {...formItemLayout}
            label="用户介绍">
            <div id="userIntro">
                {getFieldDecorator('userIntro', {
                    rules: [{
                        required: true, message: '请填写活动介绍'
                    },{
                      min: 100, message: '必须大于100个字符!'
                    }],
                    initialValue:null
                })(
                    <MobileEditor id="userIntro"/>
                )}
            </div>
        </FormItem> */}
        <FormItem
          {...formItemLayout}
          label="联系电话"
        >
          {getFieldDecorator('phone', {
            initialValue:user?user.phone:''
          })(
            <Input addonBefore={prefixSelector}/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="是否允许登录"
        >
          {getFieldDecorator('loginFlag', {
            rules: [{ required: true, message: '登录状态必须选择一个状态!' }],
            initialValue:user?user.loginFlag:'1'
          })(
            <RadioGroup name="loginFlag">
              <Radio value={'1'}>是</Radio>
              <Radio value={'0'}>否</Radio>
            </RadioGroup>
          )}
        </FormItem>
        {/*
        <FormItem
          {...formItemLayout}
          label="用户类型"
        >
          {getFieldDecorator('userType', {
            rules: [{ required: true, message: '必须选择一个用户类型!' }],
            initialValue:user?user.userType:''
          })(
            <Select
              style={{ width: 200 }}
              placeholder="选择一个用户类型"
            >
              <Option value="1">系统用户</Option>
              <Option value="2">微信用户</Option>
              <Option value="3">平台用户</Option>
            </Select>
          )}
        </FormItem>*/}
        {isOfficeRelative?
          '':
          <FormItem
            {...formItemLayout}
            label="用户角色"
          >
            {getFieldDecorator('roles', {
              rules: [{ required: true, message: '必须至少选择一个角色!' }],
              initialValue:user?user.userRoles:[]
            })(
              
              <TreeSelect treeData={roles} treeCheckable={true} showCheckedStrategy={TreeSelect.SHOW_PARENT}
                searchPlaceholder={'请至少选择一个角色'} treeCheckStrictly={true} dropdownStyle={{maxHeight:'240px'}}
              />
            )}
          </FormItem>
        }
        <FormItem
          {...formItemLayout}
          label="备注"
        >
          {getFieldDecorator('remarks',{
            initialValue:user?user.remarks:''
          })(
            <TextArea rows={4} />
          )}
        </FormItem>
        <FormItem {...tailFormItemLayout}>
          <div>
            {user && user.notAllowUpdate ? '':
            <Button loading={this.state.sumitLoad} type="primary" htmlType="submit" style={{marginRight:'10px'}}>确定</Button>}
            <Button onClick={close}>取消</Button>
          </div>
        </FormItem>
      </Form>
    );
  }
}

const WrappedUserForm = Form.create()(UserForm);
export default WrappedUserForm
